<?php
session_start();
/* this file returns the stream of posts depending upon the input parameter
 * currently there are five possible input options
 * <<<not required now>>>1. Only one post is required. In this case a post_** input will be given
 * <<<not required now>>>2. Only one post is required but for subscription, in this case the post will not  be outputted
 *    but will  be stored in a variable which will be mailed to the subscribers: input posts_**
 * 3. Posts for a circle/group is requried in which case the initials will be group_**
 * 4. Posts by a single user to be displayed on his profile is required. This includes the wall posts that she has made. in which case the input  format will be profile_**
 * 5. Posts for the home page is needed. This will be displayed when the user logs in 
 *     and will contain the posts that are included in his circles. The input format will be home
 * 	   and for posts all over gausipp, the type will be homeall
 * 6. For real time updating of feed. the format is new_<firstid>_type
 */
 


 //This code needs the script functions_shared.php. so  in case you are calling it somehow.
 // make sure that the calling script already has this functions file included
 
 // this is in case the php file is called via ajax

require_once("../connection.php");
require_once("../../functions_shared.php");
require_once("../../functions.php");

$type = $_POST['type'];
$user = $_POST['user']; // the presently logged in user
if(isset($_POST['offset']))
	$offset_text = "AND `id`< '".$_POST['offset']."'";
else
	$offset_text = "";

//echo $type.' '.$user.' '.$offset_text;


$arr = explode("_",$type);
$type1 = $arr[0];

$new_or_not = "0";
if($type1 == "new")
{
	$offset_text = "AND `timestamp`>'".$arr[1]."'";
	$type = str_replace("".$arr[0]."_".$arr[1]."_", "", $type);
	$new_or_not = "1";
		
	$arr = explode("_",$type);
	$type1 = $arr[0];
}



if($type1 == "group") // if it is called via ajax for diaplying in a circle
{	
	$result = mysql_query("SELECT * FROM site_posts WHERE `del`!='1' AND `type`='$type' ".$offset_text." ORDER BY `freshness` DESC LIMIT 10");
	if(!$result) echo mysql_error();	
}

else if($type1 == "profile")  // for the profile feed
{
	//require_once("../connection.php");
	$fbid = $arr[1];
	$anon = $arr[2];
	if($anon == "true")
	$result = mysql_query("SELECT * FROM site_posts WHERE `del`!='1' AND `user`='$fbid' ".$offset_text." ORDER BY `freshness` DESC LIMIT 10");
	else
	$result = mysql_query("SELECT * FROM site_posts WHERE `del`!='1' AND `user`='$fbid' AND `postas`!='anonymous' ".$offset_text." ORDER BY `freshness` DESC LIMIT 10");
	if(!$result) echo mysql_error();
}
else if($type1 == "home")
{
	
	$res = mysql_query("SELECT * FROM site_group_members WHERE `fbid`='$user'  AND `del`!='1'");
	while($row = mysql_fetch_array($res))	$gpid[] = $row['gpid'];
	
	// so $gpid is the array where all the group is stored			
	$n = sizeof($gpid);
	$query = "";	
	
	//selection from groups
	for($i=0;$i<$n;$i++)
		$query = $query." SELECT * FROM site_posts WHERE `type`='group_".$gpid[$i]."' ".$offset_text." AND `del`!='1' UNION";
		
		//reading posts fromher friends
		//first checking which of her frinds are on gausipp
		$user_friends = $_SESSION['friends'];
		$frns_len = sizeof($user_friends['data']);
		for($i=0;$i<$frns_len-1;$i++)
		  if(mysql_numrows(mysql_query("SELECT * FROM site_user_meta WHERE `fbid`='".$user_friends["data"][$i]["id"]."'")))
		$user_friends_on_gausipp[] = $user_friends["data"][$i]["id"];
		// now selectin from the table
		$query1 = " SELECT * FROM site_posts WHERE `type` LIKE 'wall%' AND (";
		$frns_len = sizeof($user_friends_on_gausipp);
		for($i=0;$i<$frns_len;$i++)
			$query1=$query1." `user`= '".$user_friends_on_gausipp[$i]."' OR ";
		$query1=$query1." `user`= '".$user."'";
		$query1 = $query1." ) ".$offset_text." AND `del`!='1'"; 
		
				
	$query = $query.$query1." ORDER BY `freshness` DESC LIMIT 10";
	
	$result = mysql_query($query);
	if(!$result) echo mysql_error();
		
}
else if($type1 == "homeall")
{
	$res = mysql_query("SELECT * FROM site_groups WHERE `visibility`='public' OR `visibility`='protected' AND `del`!='1'");
	while($row = mysql_fetch_array($res))	$gpid[] = $row['id'];
	$n = sizeof($gpid);
	$query = "";	
	
	// adding results from all the groups in the query
	for($i=0;$i<$n;$i++)
		$query = $query." SELECT * FROM site_posts WHERE `type`='group_".$gpid[$i]."' ".$offset_text." AND `del`!='1' UNION";
		
	//$query = $query." SELECT * FROM site_posts WHERE `type`='group_".$gpid[$n-1]."' ".$offset_text." AND `del`!='1' ORDER BY `timestamp` DESC LIMIT 10";
	
	
		// now selectin from the table
		$query1 = " SELECT * FROM site_posts WHERE `type` LIKE 'wall%' ".$offset_text." AND `del`!='1'";
		
	$query = $query.$query1." ORDER BY `freshness` DESC LIMIT 10"; 
	
	$result = mysql_query($query);
	if(!$result) echo mysql_error();
		
	
	}
// everything first will be store in a variable $output which will later be echoed and 
// this will not be done in case the input format is posts meant for subscription
$output = "";
//if(mysql_numrows($result) == 0)
	//$output=$output.'<br><span class="small-font">Nothing to show here!</span>';


	
// setting up the responses
$response_result = mysql_query("SELECT * FROM site_response_meta");
while($row1 = mysql_fetch_array($response_result))
{
	if($row1['rid'] == "1") $r1 = $row1['name'];  // for OMG 
	if($row1['rid'] == "2") $r2 = $row1['name'];  // for LOL
	if($row1['rid'] == "3") $r3 = $row1['name'];  // for AWW
}


// a variable to keep track of the lowest post id encountered for more comments
// ideally should be very large number but is given the id of the first read post later
$last_id = 0;

//bakchodi
$firstornot = "0";
$time = time();


echo $output;  // why is this?
//actual loop starts
$size = mysql_numrows($result);

//$output_final = $size."<br>";
$output_final = "";
$counterr = 0;

////////////////////////////////////////////////////// actual posts //////////////////////////////////////////////////////////////////

while($row = mysql_fetch_array($result))
{
		$output = "";
	
	// to fetch the name of the group or wall for that matter whhere the post was made	
	if($type1 == "home" || $type1 == "homeall"  || $type1 == "profile")
	{
		$type2 = $row['type'];
		$arr = explode("_",$type2);
		if($arr[0] == "group")
		{
		$gpid = $arr[1];		
		$res = mysql_query("SELECT `name` FROM site_groups WHERE `id`='$gpid'");
		$gp_name = mysql_result($res, 0, 'name');
		if($gp_name == "") $gp_name = "your circle";
		$name = '<span style="font-weight:normal" class="faded"> posted in <a href="'.$site_url.'index.php?cat=group&action=gausipp&gpid='.$gpid.'" class="faded">'.$gp_name.'</a></span>';
		}
		else if($arr[0] == "wall")
		{
			//$name = '<span style="font-weight:normal" class="faded small-font"> posted </span>';
			$name = "";
		}	
	}
	
		
	//setting some variables
	$postas = $row['postas'];
	$postid = $row['id'];
	$user_p = $row['user']; // the user who made the post
	
	//setting variables for future use
	if($postas == "anonymous") 
		$postas = "anonymous";   // changed from "anonymous"
	else
	{
		$arr = explode("_",$postas);
		$postas = '<strong style="color:#555">'.$arr[1].'
		</strong>&nbsp;';
	}
	
	// for the "posted in" statement
	if($type1 == "home" || $type1 == "homeall" || $type1 == "profile")
		$postas1 = $postas.$name;
	else if($postas == "anonymous")
		$postas1 = "";
	else
	$postas1 = $postas;
	
	// starting post
	if($firstornot == "0" && $new_or_not=="0"){	
		$last_id = 	$row['id'];
		$firstornot = "1";
	}
	
	$output = $output.'<div class="stream_post chat-bubble ';
	if($user_p == $user) $output = $output."right-chat-bubble ";
		else $output = $output."left-chat-bubble ";
	if($postas == "anonymous") $output = $output."anon-chat-bubble ";
	$output = $output.'" id="stream_post_'.$postid.'" >';
	
	
	// registering the last_id
	if((int)$row['id'] < $last_id)
	 $last_id = (int)$row['id'];
	
	$output=$output.'<div >';
	
	if($postas1 != "")
	$output=$output.'<span class="small-font faded">'.$postas1.'</span><br>';
	
	$output=$output.'<span  class="postContent">';	
	
	//processing output text
	$out = stripslashes($row['text']);
	if($out!="")  $output=$output.addTags(convertUrl($out)).'';
	
	// processing output media
	$media = $row['media'];
	if($media != "") {
	$arr = explode("_",$media);
		
	if($arr[0] == "img") { $val1 = substr($media, 4); $type2 = "img"; }
	else if($arr[0] == "vid")  { $val1 = substr($media, 4); $type2 = "vid"; }
		
	 $output=$output.'<br>';
	 include("post/attach_media.php");
	}
	
	$output=$output.'</span>';				
	$output=$output.'<div class="clear"></div></div>';	
	$output=$output.'</div><div class="clear"></div>';	
	
	
	//displaying the output
	$output_final =  $output.$output_final;
	
}

	//echo '<div style="background:#fee">'.$output_final.'</div>';
	$output = "";

if(($size!=0) && (($offset_text=="") || ($offset_text!="" && $new_or_not == "1")))
$output_final = $output_final.'<div class="stream_new" id="new_'.$time.'_'.$type.'"></div>';

///////////////////////////////////////////////////////////////// loop end //////////////////////////////////////////////////////////////////
// storing the last read information in the user's database
if($type1 == "group")
{
	if(mysql_num_rows(mysql_query("SELECT * FROM site_read WHERE `fbid`='$user' AND `type`='$type'"))!=0)
		mysql_query("UPDATE site_read SET `timestamp`='$time' WHERE `type`='$type' AND `fbid`='$user'");
	else 
		mysql_query("INSERT INTO site_read ( `type`, `fbid`, `timestamp`) VALUES ( '$type', '$user', '$time')");
}


////////////////////////////////////////////////////////////////// trailer ///////////////////////////////////////////////////////////////////

// for the more posts link
if(mysql_numrows($result)!=0) {
	/*if(isset($_POST['offset']) && mysql_numrows($result) == 10){  // this is for more
		$output =  '<div class="a stream_more" onclick=\'init_stream("'.$user.'", "'.$type.'",'.$last_id.')\' id="'.$type.'_more" style="margin-top:10px;">More</div>';
	}	*/
	//else 
	if($new_or_not == "1"){
		// nothing required to be done
		$output = "";
		}
	else if($size==10){// its the normal stream, no shit, no guns
		$output = '<div class="a stream_more" onclick=\'init_stream("'.$user.'", "'.$type.'",'.$last_id.')\' id="'.$type.'_more" style="margin-top:10px;">More</div>';
	}
}
else { // the number of rows was 0, this gets tricky
	if(isset($_POST['offset'])){  // this is for more
		$output = '<div class="stream_more" style="margin-top:10px;">Nothing more here!</div>';
	}
	else if($new_or_not == "1"){
		//echo '<div class="stream_new" id="new_'.$time.'_'.$type.'"></div>';
		$output = "";
		}
	else {
		if($type1 == "home") {
		$output = '<div class="stream_new" id="new_'.$time.'_'.$type.'">
		<span>This place will show all the latest gaussip from your circles. Since we have nothing to show right now, consider<Br><Br>
		creating a <span class="medium-menu" style="padding:5px;" >
		<span class="menu-text"><a href="index.php?cat=group&action=create">new cirle</a></span>
		</span> or posting in your existing circles.
		'; 
		
		
		// this resource is already done once while generating the chat list in the header
		//echo mysql_numrows($result_user_friends);
		$user_friends = $_SESSION['friends'];
		$query = "SELECT * FROM site_user_meta WHERE ";
		$frns_len = sizeof($user_friends['data']);
		for($i=0;$i<$frns_len-1;$i++)
			$query=$query." `fbid`= '".$user_friends["data"][$i]["id"]."' OR ";
		
		$query=$query." `fbid`= '".$user_friends["data"][$frns_len-1]["id"]."'";
		$result_user_friends = mysql_query($query);
		if(mysql_numrows($result_user_friends) != 0) {
			$output = $output."<br><br>Your friends on Gausipp<br>";			
			$output = $output.disp_user($result_user_friends, "gen", $user,"return");
		}
		$output = $output.'</div>';
		}
		else	
		$output = $output.'<div class="stream_new" id="new_'.$time.'_'.$type.'">Nothing here yet!</div>';
	}
}

$output_final = $output.$output_final;
echo $output_final;
?>